package com.zhangdi.demo.rabbitmq.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author zhangdi
 * @version 1.0
 * @date 2021.11.2 11:17
 */
public class Send {
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("1.12.225.29");
        factory.setVirtualHost("/");
        factory.setPort(5672);
        factory.setUsername("worker0");
        factory.setPassword("worker0");

        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare("producer", false, false,false, null);

            channel.basicPublish("", "producer", null, "搞笑".getBytes(StandardCharsets.UTF_8));
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }finally {
            if(null != channel && channel.isOpen()){
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(null != connection && connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
